$(window).bind('load', null, function() {
	prepareEntryTable();
	bindToNewEntry();
	startTimer();
})

function startTimer() {
	setInterval(updateTimers, 5 * 1000);
}

function updateTimers() {
	$('#entries tr.running').each(function() {
		var msecsSinceStart = Number($('input[name="timerStarted"]', this).val());
		var secsTotal = Number($('input[name="entry.seconds"]', this).val());
		var msecsTimed = (new Date().getTime() - msecsSinceStart) + (secsTotal * 1000);
		var timeString = getTimeString(msecsTimed);
		$('input[name="entry.count"]', this).each(function() {
			parent = findParent(this, 'td');
			$('span.label', parent).empty().append(timeString)
		});
	});
}

function getTimeString(millis) {
	var tsecs = millis / 1000;
	var tmins = tsecs / 60;
	var thours = tmins / 60;
	
	var timeStr = "";
	timeStr += Math.floor(thours);
	var rmins = Math.floor(tmins) % 60;
	timeStr += ":" + (rmins > 9 ? String(rmins) : "0" + String(rmins));
	return timeStr;
}

function toggleTimer(element) {
	var toggle = $(element).attr('href').substring(1); 
		var node = findParent(element, 'tr');
		var ser = $('input, select', node).serialize();
		jQuery.post(BASEURL + "remote/" + toggle + "Timer.html?ajax=true&day=" + DAY, ser, 
			function(responseXML) {
				updateTable(responseXML);
			})
}

function updateEntry(element) {
	tr = findParent(element, 'tr');
	var ser = $('input, select', tr).serialize();
	jQuery.post(BASEURL + "remote/updateTimer.html?ajax=true&day=" + DAY, ser, 
			function(responseXML) {
				updateTable(responseXML);
			})
			
}


function bindToNewEntry() {
	$('#new-project').bind('change', null, function() {
		var selected = $(this).val();
		var select = $('#new-category');
		select.html('<option></option>')
		var categories = CATEGORIES[selected];
		for (var i = 0; i < categories.length; i++) {
			var cat = categories[i];
			select.append('<option value=' + cat.id + '>' + cat.name + '</option>');
		}
	});
}

function bindToTimerLinks() {
	$('#entries a[href="#stop"], #entries a[href="#start"]').bind('click', null, function() {
		toggleTimer(this);
		return false;
	});
	
	$('#entries a[href="#update"]').bind('click', null, function() {
		updateEntry(this);
		return false;
	})
}

function isEntryEnabled(row) {
	return !$('span.input', row).hasClass('hidden')
}

function bindToTableRows() {

	$('#entries select[name="entry.projectId"]').bind('change', null, function() {
		populateCategorySelect(this);
	})
	
	$('#entries tr').bind('click', null, function() {
		
		// don't allow editing two things at once
		if ($('table.editable-rows').size() == 0) {
			return;
		}
		
		if (!isEntryEnabled(this)) {
			$(this).addClass('selected');
			$('table.timer-entries').removeClass('editable-rows');
			$('input[name="edited"]').val("true");
			$('span.input', this).removeClass('hidden');
			$('span.label', this).addClass('hidden');
			$('a[href="#update"]', this).show();
			
			// don't allow editing of running time field
			if (isTimerRunning(this)) {
				$('input[name="entry.count"]', this).each(function(idx) {
					var td = findParent(this, 'td');
					$('span.input', td).addClass('hidden');
					$('span.label', td).removeClass('hidden');
				});
			}
		}
	});
	
}

function isTimerRunning(trow) {
	return $('input[name="running"]', trow).val() == 'true'
}

function prepareEntryTable() {
	bindToTimerLinks();	
	bindToTableRows();
	populateTableRows();
}

function updateTable(html) {
	$('table#entries').replaceWith(html);
	prepareEntryTable();
}

function populateTableRows() {
	$('table#entries select[name="entry.projectId"]').each(function(i) {
		populateCategorySelect(this);
	})
}

function findParent(element, elementName) {
	while (element.nodeName.toLowerCase() != elementName && element != null) {
		element = element.parentNode;
	}
	return element;
}

function populateCategorySelect(projectSelect) {
	var parent = findParent(projectSelect, 'tr');
	var selectedId = $('input[name="curProjectCategoryId"]', parent).val()
	$('select[name="entry.categoryId"]', parent).each(function(i) {
		var options = createCategoryOptions($(projectSelect).val(), selectedId)
		$(this).html(options);
	})
}

function createCategoryOptions(projectId, selectedId) {
	var cats = CATEGORIES[projectId];
	var str = "<option></option>";
	for (var i = 0; i < cats.length; i++) {
		var cat = cats[i];
		str += '<option value=' + cat.id;
		if (selectedId == cat.id) {
			str += " selected='selected'";
		}
		str += '>' + cat.name + '</option>';
	}
	return str;
}